/**
 *  @file SocketToggleBlockingState.h
 */
#ifndef _SOCKETTOGGLEBLOCKINGSTATE_H_
#define _SOCKETTOGGLEBLOCKINGSTATE_H_

#include "../../common/NoCopyAndNew.h"

namespace cppflib
{

namespace net
{

/**
 *  This is used internally by Socket class to change a socket to 
 *  blocking/non-blocking mode and restore to its original mode 
 *  automatically upon exiting a function
 */
class SocketToggleBlockingState : public NoCopyAndNew
{
private:
   Socket *pSock;
   bool orgBlockingState;
public:
   /**
    *  @param [in] setBlocking -- true: set socket to blocking mode
    *                             false: non-blocking
    */
   SocketToggleBlockingState(Socket *pSock, bool setBlocking)
   {
      this->pSock = pSock;
      orgBlockingState = pSock->IsBlocking();
       
      if (orgBlockingState != setBlocking)
         pSock->SetBlocking(setBlocking);  // set to blocking/non-blocking if not already
   }
       
   ~SocketToggleBlockingState()
   {
      if (orgBlockingState != pSock->IsBlocking())
         pSock->SetBlocking(orgBlockingState);   // restore if necessary
   }
};

} // end of namespace net

} // end of namespace cppflib



#endif
